/**
 *
 * @description: 话题
 * @author: junyong.hong
 * @createTime: 2019/9/25
 * @version: 1.0.0.0
 * @history:
 *    1、
 *    2、
 *
 */
const Topic = require('../models/topics')
const User = require('../models/users')
const Questions = require('../models/questions')

class TopicsCtl {
    // 查询所有话题
    async find(ctx) {
        const { per_page = 10 } = ctx.query

        // 当前第几页
        const page = Math.max(ctx.query.page * 1, 1) - 1
        // 每页有多少项
        const perPage = Math.max(per_page * 1, 1)

        // limit(10)只返回10项
        // skip(10)跳过前10项
        // limit(10).skip(10) 返回第二页，跳过前10条数据

        // page 1
        // perPage 10
        ctx.body = await Topic.find({ name: new RegExp(ctx.query.q) })
                              .limit(perPage).skip(page * perPage)
    }

    // 查询指定话题
    async findById(ctx) {
        const { fields = '' } = ctx.query
        const selectFields = fields.split(';').filter(f => f).map(f => ' +' + f).join('')
        const topic = await Topic.findById(ctx.params.id).select(selectFields)
        ctx.body = topic
    }

    // 创建话题
    async create(ctx) {
        // 校验
        ctx.verifyParams({
            name: { type: 'string', required: true },
            avatar_url: { type: 'string', required: false },
            introduction: { type: 'string', required: false },
        })

        const topic = await new Topic(ctx.request.body).save()
        ctx.body = topic
    }

    // 修改话题
    async update(ctx){
        // 校验
        ctx.verifyParams({
            name: { type: 'string', required: false },
            avatar_url: { type: 'string', required: false },
            introduction: { type: 'string', required: false },
        })

        const topic = await Topic.findByIdAndUpdate(ctx.params.id, ctx.request.body)
        ctx.body = topic
    }

    // 获取关注该话题的粉丝
    async listTopicFollowing(ctx, next) {
        const users = await User.find({ followingTopics: ctx.params.id })
        ctx.body = users
    }

    // 校验话题是否存在
    async checkTopicExist(ctx, next) {
        const topic = await Topic.findById(ctx.params.id)
        if (!topic) {
            ctx.throw(404, '话题不存在')
        }
        await next()
    }

    // 获取某个话题的问题列表
    async listQuestions(ctx) {
        const questions = await Questions.find({
            topics: ctx.params.id
        })
        ctx.body = questions
    }
}

module.exports = new TopicsCtl()